﻿using Microsoft.Win32;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WeChatTool
{
	public partial class frmMain : UIForm
	{
		public frmMain()
		{
			InitializeComponent();
		}

		/// <summary>
		/// 消息队列
		/// </summary>
		QueueLength<string> _queue = new QueueLength<string>(20);
		int _count=0;

		#region 载入、关闭
		private void frmMain_Load(object sender, EventArgs e)
		{
			this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
			this.notifyIcon1.Icon = this.Icon;
			txtWeChat.Text = FileUtil.GetWeChatPath();
			txtFolder.Text = FileUtil.GetFolder(txtWeChat.Text.RemoveRight(10));
			start(txtWeChat.Text);
			Run(txtFolder.Text);
			this.WindowState = Properties.Settings.Default.ShowUI ? FormWindowState.Normal : FormWindowState.Minimized;
			this.tslVersion.Text = $"版本{Assembly.GetExecutingAssembly().GetName().Version}";
			//CreateStartup();
		}

		private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (MessageBox.Show("退出后微信文件只读不能改写，确定要退出程序吗？", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.OK)
				e.Cancel = true;

		}
		#endregion


		private void Run(string path)
		{
			if (!Directory.Exists(path))
			{
				Print($"指定目录[{path}]有误！");
				uliState.State = UILightState.Off;
				btnRun.Enabled = true;
			}
			else
			{
				//初始化监控器
				FileWatcher watcher = new FileWatcher(path);
				watcher.Open();
				var task = new Task(obj =>
				{
					FileChangeInformation fci = null;
					//获取消息
					while (true)
					{
						Thread.Sleep(500);
						//如果IsWatch为False，则可能监控内部发生异常终止了监控，需要重新开启监控
						if (watcher.IsWatch)
						{
							fci = watcher.Get();
							if (!(fci is null))
							{
								try
								{
									if (FileUtil.CancelReadOnly(fci.FullPath))
									{
										Print($"改为可写：{fci.Name}");
										_count++;
										this.tslCount.Text= $"处理文件[{_count}]";
									}
									else if (this.swtShowOther.IsPress)
										Print(fci.ToString());
								}
								catch (Exception)
								{
									Thread.Sleep(500);
									watcher.Push(fci);
								}
							}
						}
						else
						{
							watcher.Open();
						}						
					}
				}, null, TaskCreationOptions.LongRunning);
				task.Start();
				Print("开始处理微信接收到的文件...");
				uliState.State = UILightState.On;
				btnRun.Enabled = false;

				Task taskBat = Task.Factory.StartNew(() =>
				{
					int count= FileUtil.BatchCancelReadOnly(path);
					if (count > 0)
					{
						Print($"处理微信接收到的历史文件[{count}]个。");
						_count += count;						
					}
				});
			}
		}


		
		private void Print(string log)
		{
			_queue.Enqueue(log);
			this.txtLog.Invoke(new Action(() =>
			{
				this.txtLog.Text=_queue.ToString();
				this.tslCount.Text = $"处理文件[{_count}]";
			}));

		}

		private void btnRun_Click(object sender, EventArgs e)
		{
			
			if (Directory.Exists(txtFolder.Text))
			{
				if (string.IsNullOrEmpty(Properties.Settings.Default.Folder) ||Properties.Settings.Default.Folder != txtFolder.Text)
				{
					Properties.Settings.Default.Folder = txtFolder.Text;
					Print($"微信文件保存目录设置为{Properties.Settings.Default.Folder}");
				}
				Run(txtFolder.Text);
			}
			else
			{
				Print("微信文件保存目录有误，请选择。");
				btnFolder_Click(sender, e);
			}

		}

		private void btnFolder_Click(object sender, EventArgs e)
		{
			FolderBrowserDialog dialog = new FolderBrowserDialog();
			dialog.Description = "请选择微信文件保存目录";			
			if (dialog.ShowDialog() == DialogResult.OK)
			{
				if (!dialog.SelectedPath.EndsWith("FileStorage\\File", StringComparison.CurrentCultureIgnoreCase) &&
					MessageBox.Show("目录应选微信用户名下的[FileStorage\\File]，是否重新选择？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
				{
					btnFolder_Click(sender,e);
				}
				else
				{
					string foldPath = dialog.SelectedPath;
					this.txtFolder.Text = foldPath;
					Properties.Settings.Default.Folder = foldPath;
				}
			}
		}



		#region 窗口大小改变
		private void frmMain_SizeChanged(object sender, EventArgs e)
		{
			switch (this.WindowState)
			{
				case FormWindowState.Minimized:
					this.ShowInTaskbar = false;
					this.Hide(); //或者是this.Visible = false;
					this.notifyIcon1.Visible = true;
					break;
				case FormWindowState.Maximized:
				case FormWindowState.Normal:
				default:
					this.ShowInTaskbar = true;
					break;
			}

		}



		private void notifyIcon1_DoubleClick(object sender, EventArgs e)
		{
			if (this.WindowState == FormWindowState.Normal)
			{
				this.WindowState = FormWindowState.Minimized;
				this.Hide();
			}
			else if (this.WindowState == FormWindowState.Minimized)
			{
				this.Show();
				this.WindowState = FormWindowState.Normal;
				this.Activate();
			}

		}

		private void swtShowUI_ValueChanged(object sender, bool value)
		{
			Properties.Settings.Default.ShowUI = swtShowUI.Active;
			this.WindowState = Properties.Settings.Default.ShowUI ? FormWindowState.Normal : FormWindowState.Minimized;
		}
		#endregion



		/// <summary>
		/// 为当前程序创建后台启动文件到 开机启动文件夹
		/// </summary>
		void CreateStartup()
		{
			var starupPath = GetType().Assembly.Location;//获得程序路径其他方式也可以
			try
			{
				var fileName = starupPath;
				var shortFileName = fileName.Substring(fileName.LastIndexOf('\\') + 1);
				//打开子键节点
				var myReg = Registry.LocalMachine.OpenSubKey(
					"SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Run", RegistryKeyPermissionCheck.ReadWriteSubTree,
					RegistryRights.FullControl);
				if (myReg == null)
				{
					//如果子键节点不存在，则创建之
					myReg = Registry.LocalMachine.CreateSubKey("SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Run");
				}
				if (myReg != null && myReg.GetValue(shortFileName) != null)
				{
					//在注册表中设置自启动程序
					myReg.DeleteValue(shortFileName);
					myReg.SetValue(shortFileName, fileName);

				}
				else if (myReg != null && myReg.GetValue(shortFileName) == null)
				{
					myReg.SetValue(shortFileName, fileName);

				}
			}
			catch
			{

			}
		}

		#region 启动微信主程序
		private void btnExe_Click(object sender, EventArgs e)
		{
			OpenFileDialog dialog = new OpenFileDialog();
			dialog.Multiselect = false;//该值确定是否可以选择多个文件
			dialog.Title = "请选择微信主程序";
			dialog.Filter = "微信主程序|WeChat.exe";
			if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				string file = dialog.FileName;
				this.txtWeChat.Text = file;
				Properties.Settings.Default.WeChat = file;
			}
		}

		private void btnStart_Click(object sender, EventArgs e)
		{
			if (File.Exists(txtWeChat.Text))
			{
				if(string.IsNullOrEmpty(Properties.Settings.Default.WeChat) || Properties.Settings.Default.WeChat != txtWeChat.Text)
				{
					Properties.Settings.Default.WeChat = txtWeChat.Text;
					Print($"微信主程序位置设置为{Properties.Settings.Default.WeChat}");
				}
				start(txtWeChat.Text);
			}
			else
			{
				Print("微信主程序位置有误，请选择。");
				btnExe_Click(sender, e);
			}
		}


		private void start(string path)
		{
			if (checkRunning())
			{
				Print($"微信运行中...");
			}
			else if (path.EndsWith("WeChat.exe", StringComparison.CurrentCultureIgnoreCase) &&
				File.Exists(path))
			{
				Process p = Process.Start(path);
			}
			else 
			{
				Print($"微信主程序位置有误，请重新选择！\r\n{path}");
			}			
		}
		#endregion




		



		private bool checkRunning()
		{
			Process[] processes = Process.GetProcessesByName("wechat");
			return processes.Length > 0;
		}
	}
}
